/*******************************************************************************
 * Copyright (c) 2010, 2017 西安秦晔信息科技有限公司
 * Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *******************************************************************************/
package com.qinyeit.configuration;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import static com.qinyeit.serviceapp.constans.Constants.MERCHANT_TO_GROUP_EXCHANGE;
import static com.qinyeit.serviceapp.constans.Constants.QUEUE_MERCHANT_GROUP;
import static org.springframework.amqp.core.Binding.DestinationType.QUEUE;

/**
 * <p>ClassName: com.qinyetech.webapp.RabbitConfiguration
 * <p>Function: RabbitMQ配置
 * <p>date: 2018-01-26 13:09
 *
 * @author wuqing
 * @version 1.0
 * @since JDK 1.8
 */
@Configuration
@EnableRabbit
public class RabbitConfiguration {

    /**
     * 因为要为RabbitTemplate设置回调，所以需要设置为prototype
     * @param connectionFactory
     * @return
     */
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        return template;
    }

    @Bean
    public RabbitAdmin amqpAdmin(CachingConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin=new RabbitAdmin(connectionFactory);
        //类型为direct ,无需指定routingKey
        rabbitAdmin.declareExchange(new DirectExchange(MERCHANT_TO_GROUP_EXCHANGE,true,false));
        rabbitAdmin.declareQueue(new Queue(QUEUE_MERCHANT_GROUP,true,false,false));
        rabbitAdmin.declareBinding(new Binding(QUEUE_MERCHANT_GROUP,QUEUE,MERCHANT_TO_GROUP_EXCHANGE,QUEUE_MERCHANT_GROUP,null));
        return rabbitAdmin;
    }
}
